package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类（订单状态）
 */
@Component//会被实例化，加入spring容器处理
public class OrderTask
{
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder()
    {
        System.out.println("定时处理超时订单：{}"+ LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //查询处于代付款的状态和下单时间
        List<Orders> list = orderMapper.getStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);
        if(list != null && list.size() > 0)
        for (Orders od: list)
        {
            od.setStatus(Orders.CANCELLED);
            od.setCancelReason("订单超时，自动取消");
            od.setCancelTime(LocalDateTime.now());
            orderMapper.update(od);
        }
    }

    /**
     * 处理一直处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder()
    {
        System.out.println("定时处理超时订单：{}"+ LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        //查询处于一直派送中的的状态和下单时间
        List<Orders> list = orderMapper.getStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if(list != null && list.size() > 0)
            for (Orders od: list)
            {
                od.setStatus(Orders.COMPLETED);
                od.setCancelReason("订单派送时间超时，自动取消");
                od.setCancelTime(LocalDateTime.now());
                orderMapper.update(od);
            }
    }
}
